package com.financing.wap.web.controller.api;


import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.mail.dto.MailContentDTO;
import com.financing.mail.service.MailSenderService;
import com.financing.wap.activities.ActivitiesBusinessObject;
import com.financing.wap.activities.impl.ActivitiesYLYXHDImpl;
import com.financing.wap.common.CommonConstantUtil;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.common.Session;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dto.AccountDetailDTO;
import com.financing.wap.dto.CorpFaUserDTO;
import com.financing.wap.dto.FaUserDTO;
import com.financing.wap.dto.FaUserWechatDTO;
import com.financing.wap.dto.MailRecordDTO;
import com.financing.wap.dto.ProductAttachmentDTO;
import com.financing.wap.dto.ProductDetailPageDTO;
import com.financing.wap.dto.RegisterDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IAccountService;
import com.financing.wap.service.IActivitesService;
import com.financing.wap.service.IActivitieGiftService;
import com.financing.wap.service.ICheckCodeService;
import com.financing.wap.service.IProductService;
import com.financing.wap.service.IRegisterService;
import com.financing.wap.service.ISmsService;
import com.financing.wap.service.IUserService;
import com.financing.wap.service.IUserWechatService;
import com.financing.wap.service.IWechatCoreService;
import com.financing.wap.util.Constants;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.IPUtil;
import com.financing.wap.util.MessageUtil;
import com.financing.wap.util.PropertiesUtils;
import com.financing.wap.util.RandomUtils;
import com.financing.wap.util.SecureUtil;
import com.financing.wap.util.VerifyCodeUtils;
import com.financing.wap.web.controller.BaseController;


/**
 * 平台活动专属controller
 * @author Mars
 * @createDate 2014年10月28日
 */
@Controller("apiActivityController")
@RequestMapping("/api/activity")
public class ActivityController extends BaseController {
	Logger logger = Logger.getLogger(getClass());

	@Autowired
	private IUserService userService;

	@Autowired
	public ISmsService smsService;

	@Autowired
	private IAccountService accountService;

	@Autowired
	private MailSenderService mailSenderService;

	@Autowired
	private IProductService productService;
	
	@Autowired
	private ICheckCodeService checkCodeServiceImpl;
	
	@Autowired
	private IRegisterService registerService;
	
	@Autowired
	private IActivitesService activitesServiceImpl;
	
	@Autowired
	private IWechatCoreService wechatCoreServiceImpl;
	
	@Autowired
	private IUserWechatService userWechatServiceImpl;
	
	//2016元宵活动-统计
	public static AtomicInteger ylyxhd_count = new AtomicInteger(7559);
	
	@Autowired
	private IActivitieGiftService activitieGiftServiceImpl;
	/**
	 * 活动注册接口
	 * @param mobile 手机号
	 * @param vCode 验证码
	 * @param sourceCode 来源码
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("activityResiter")
	@ResponseBody
	public ResultMap activityRegister(String mobile,String vCode,String sourceCode,HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		//		request.getSession().setAttribute(name, value);
		if(StringUtils.isBlank(mobile)||StringUtils.isBlank(vCode)){
			//参数验证
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
			result.setMessage("mobile or vCode is null!");
			return result;
		}

		try {
			if(userService.isMobileRegistered(mobile)){
				logger.info("activity resiter repeat mobile no");
				//已经被注册
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_MOBILE_NUMBER_CONFLICT);
				result.setMessage("手机号码已经被注册！");
				return result;
			}
			Integer activety_otp_time= new Integer(PropertiesUtils.getValue("activety_otp_time")); 
			logger.info("start check OTP~");
			logger.info("activity time is "+activety_otp_time+" m");
			if(checkCodeServiceImpl.CheckCodeSwitch() && checkOtpCodeTimeOut(mobile,activety_otp_time,ISmsService.OTP_CODE_FIRST_TIME)){//验证短息30分钟内有效
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OTP_VALIDATE_ERROR_TIMEOUT);
				result.setMessage("手机验证码超时！");
				return result;
			};

			if(checkCodeServiceImpl.CheckCodeSwitch() && !vCode.equalsIgnoreCase(getOtpCode(mobile))){//验证码校验
				log.info("error otpcode");
				//校验验证码--未通过
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OTP_VALIDATE_ERROR);
				result.setMessage("手机验证码不正确！");
				return result;
			}
			log.info("activity start register");
			//对密码进行加密
			String password = VerifyCodeUtils.generateVerifyCode(6,VerifyCodeUtils.VERIFY_CODES_NUM);
			String securePassword = SecureUtil.MD5EncryptAndBase64(password);

			UserDTO user = new UserDTO();
			user.setLoginName(mobile);
			user.setMobile(mobile);
			user.setPassword(securePassword);
			String sourceCodeInt = "0";
			
			//加入广告来源注册sourceCode
			String mid = (String) SessionUtil.getSession().getAttribute("mid");
			if(StringUtils.isNotBlank(sourceCode)){
				sourceCodeInt = sourceCode;
			}
			user.setMediaSource(mid);
			user.setRemark((String)SessionUtil.getSession().getAttribute("wi"));
			user.setSourceCode(sourceCodeInt);
			//创建用户
			userService.registerUser(user);
			//自动登录
			user = userService.getUserByUF(user);
			Session session = getSession(true);
			session.setLogin(true);
			session.setUser(user);
			
			FaUserDTO userTmp = new FaUserDTO();
			userTmp.setId(user.getId());
			userTmp.setLastLoginIP(IPUtil.getRemoteHost(request));
			userTmp.setLastLoginTime(new Date());
			userService.updateFaUserInfo(userTmp);
			
			setSession(session);
			result.setAttribute("id", user.getId());
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setMessage("注册成功!");

			logger.info("获取活动短信信息");


			/****注入1111返利明细****/

			//			activety_endDate_Str
			String activityEndStr = request.getParameter("aeds");
			if(StringUtils.isBlank(activityEndStr)){
				activityEndStr = PropertiesUtils.getValue("activety_endDate_Str");
			}
			//当前时间
			Calendar currentCalendar = Calendar.getInstance();
			currentCalendar.setTime(new Date());

			//活动结束时间
			Calendar activityEndCalendar = Calendar.getInstance();
			activityEndCalendar.setTime(DateUtil.parseDateString(activityEndStr, "yyyy-MM-dd"));
			if(currentCalendar.before(activityEndCalendar)){
				AccountDetailDTO dto = new AccountDetailDTO();
				dto.setAccountId(user.getAccountId());
				dto.setAmount(new BigDecimal(PropertiesUtils.getValue("activety_register_money")));
				dto.setUserId(user.getId());
				dto.setRemark(PropertiesUtils.getValue("activety_title"));
				accountService.addUserAccountDetailByActivityGift(dto,sourceCodeInt);
			}
			/****将随机密码发送至客户手机****/
			Map<String,Object>  params = new HashMap<String,Object>();
			//			passWordc
			params.put("passWord", password);
			Map<String,Object> m  = MessageUtil.getMessage("messageAndMail","activityRegister",params);
			//			String title = (String)m.get(MessageUtil.KEY_TITLE);
			String content = (String)m.get(MessageUtil.KEY_CONTENT);
			logger.info("将随机密码发送至客户手机");

			smsService.sendOtpMessage(mobile, content,Constants.regPasswdSmsAd);

			return result;
		}catch(Exception e) {
			logger.error("==>error messang:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			result.setMessage("注册失败!");
		}
		return result;
	} 

	/**
	 * 分享活动接口
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/share")
	@ResponseBody
	public ResultMap activityShare(String mobile,String vCode,HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();

		try{
			String sourceCode = request.getParameter("sourceCode");
			if(StringUtils.isBlank(sourceCode)){
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_NO_SOURCE_CODE);
				result.setMessage("没有sourceCode");
				return result;
			}
			String userId = sourceCode;
			CorpFaUserDTO userInfo = userService.getUserById(userId);
			//登录人信息
			FaUserDTO updateDTO = new FaUserDTO();
			updateDTO.setForwardNum(userInfo.getForwardNum()+1);
			updateDTO.setId(userInfo.getId());
			updateDTO.setUpdateBy(userInfo.getId().toString());
			userService.updateFaUserInfo(updateDTO);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setMessage("转发成功!");
		}catch(Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			result.setMessage("转发失败!");
		}
		return result;
	} 

	/**
	 * 邮件分享活动接口，注：便于loginfilter中做过滤条件。
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/mail/share")
	@ResponseBody
	public ResultMap activityShareMail(String mailAddress,Integer pid,HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		if(StringUtils.isBlank(mailAddress)){
			logger.info("mail address is null~~");
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_VALIDATE_ERROR);
			result.setMessage("邮件地址为null!");
			return result;
		}
		if(null==pid){
			logger.info("pid is null~~");
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_VALIDATE_ERROR);
			result.setMessage("产品id为null!");
			return result;
		}
		Session session = getSession(true);
		UserDTO loginUser = session.getUser();
		if(loginUser==null){
			result.setStatus(STATUS.NEED_LOGIN);
			result.setStatusCode(ResultMap.LOGIN_NOLOGIN_ERROR);
			result.setMessage("转发失败,未登录!");
			return result;
		}
		try{
			logger.info("apply order start send mail");
			ProductDetailPageDTO productDTO = productService.getProductDetailView(pid);
			Map<String,Object> parames  = new HashMap<String,Object>();


			parames.put("homeUrl", PropertiesUtils.getValue("ctxPath"));//网站地址
			parames.put("pCode", productDTO.getProductCode());//产品代码
			parames.put("pName", productDTO.getProductName());//产品名称
			parames.put("annualRevenueExpect", productDTO.getProfitHight().getExpectAnnualRevenue());//预期年化收益
			parames.put("pType", productDTO.getProductType());//产品类别
			parames.put("pProfitType", productDTO.getpProfitType());//收益类型
			parames.put("investType", productDTO.getInvestType());//投资领域
			parames.put("paymentInterestType", productDTO.getPaymentInterestType());//付息方式
			parames.put("issuingScale", productDTO.getAllIssuingScale().toEngineeringString());//募集规模
			parames.put("dueTime", productDTO.getDueTime().toString());//产品期限
			parames.put("saleDateStart",DateUtil.formatDate(productDTO.getSaleDateStart(), "yyyy-MM-dd") );//起购时间
			parames.put("minimumAmount", (String.valueOf((productDTO.getMinimumAmount().multiply(new BigDecimal(0.0001))).intValue())));//起购金额
			parames.put("summary", productDTO.getSummary());//产品说明
			parames.put("attachments", getAttachments(productDTO.getProductId()));
			parames.put("pRecruitmentSummary", productDTO.getpRecruitmentSummary());//募集说明
			if(StringUtils.isNotBlank(productDTO.getpRecruitmentSummary())){
				parames.put("pRecruitmentSummaryStyle","background:#FF2400; color:#fff;padding:5px;");//募集说明
//				
			}else{
				parames.put("pRecruitmentSummaryStyle"," ");//募集说明
			}
			parames = getViewParames(parames);
			Map<String,Object> m  = MessageUtil.getMessage("mailTemplate","shareMail",parames);
			String title = (String)m.get(MessageUtil.KEY_TITLE);
			String content = (String)m.get(MessageUtil.KEY_CONTENT);

			MailContentDTO mail = new MailContentDTO();
			mail.setContext(content);
			mail.setRecAddress(mailAddress);
			mail.setSubject(title+"--"+productDTO.getProductShortName());
			mail.setRequestTime(new Date());
			mailSenderService.send(mail); 
			logger.info("===邮件发送成功，开始插入记录===");
			MailRecordDTO mailRecord = new MailRecordDTO();
			mailRecord.setShareTime(new Date());
			mailRecord.setShareUserId(loginUser.getId());
			mailRecord.setShareProductId(productDTO.getProductId());
			mailRecord.setReceiverMail(mailAddress);
			mailRecord.setRemark(productDTO.getProductCode());
			productService.insertMailRecord(mailRecord);

		}catch(Exception e) {
			logger.info("sharePEVC action erro:"+e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_EMAIL_SHARE_EXCEPTION);
			result.setMessage("分享邮件发送失败!");
			return result;
		}
		result.setStatus(STATUS.SUCCESS);
		result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		result.setMessage("邮件发送成功！");
		return result;
	} 
	
	/**
	 * 邮件分享活动接口，注：便于loginfilter中做过滤条件。pevc产品
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/mail/sharePevc")
	@ResponseBody
	public ResultMap activityShareMailPEVC(String mailAddress,Integer pid,HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		Session session = getSession(true);

		if(StringUtils.isBlank(mailAddress)){
			logger.info("mail address is null~~");
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_VALIDATE_ERROR);
			result.setMessage("邮件地址为null!");
			return result;
		}
		if(null==pid){
			logger.info("pid is null~~");
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_VALIDATE_ERROR);
			result.setMessage("产品id为null!");
			return result;
		}
		UserDTO loginUser = session.getUser();
		if(loginUser==null){
			result.setStatus(STATUS.NEED_LOGIN);
			result.setStatusCode(ResultMap.LOGIN_NOLOGIN_ERROR);
			result.setMessage("转发失败,未登录!");
			return result;
		}
		try{
			logger.info("apply order start send mail");
			ProductDetailPageDTO productDTO = productService.getProductDetailView(pid);
			Map<String,Object> parames  = new HashMap<String,Object>();
			
			//产品名称：发行机构：组织形式：基金类型：起购金额：认购费：募集状态：募集说明：
			//募集规模，理财师佣金，投资期限：管理机构：收益分成：管理费：产品介绍
			parames.put("homeUrl", PropertiesUtils.getValue("ctxPath"));//网站地址
			if(productDTO.getAnnualRevenueExpect()==null){
				parames.put("annualRevenueExpect","");
			}else{
				parames.put("annualRevenueExpect",productDTO.getAnnualRevenueExpect());
			}
			if(productDTO.getProfitHight()!=null){
				if(productDTO.getProfitHight().getpIsAgreement()==null){
					parames.put("isAgreement", "");
				}else{
					parames.put("isAgreement", productDTO.getProfitHight().getpIsAgreement());
				}
			}else{
				parames.put("isAgreement", "");
			}
			
			parames.put("pName", productDTO.getProductName());//产品名称
			parames.put("investOwner", productDTO.getInvestOwner());//发行机构
			parames.put("peOrganizeShape", productDTO.getPeOrganizeShape());//组织形式
			parames.put("peFundShape", productDTO.getPeFundShape());//基金类型
			if(productDTO.getMinimumAmount()==null){
				parames.put("minimumAmount", "0");
			}else{
				parames.put("minimumAmount", (String.valueOf((productDTO.getMinimumAmount().multiply(new BigDecimal(0.0001))).intValue())));//起购金额
			}
			if(productDTO.getPeSubscriptionFee()==null){
				parames.put("peSubscriptionFee", "0");
			}else{
				parames.put("peSubscriptionFee", (String.valueOf((productDTO.getPeSubscriptionFee().multiply(new BigDecimal(1.00))).doubleValue())));//认购费
			}
			
			parames.put("saleStatus", productDTO.getSaleStatus());//募集状态
			parames.put("publicArea", productDTO.getPublicArea());//发行地区  
			parames.put("rebate", productDTO.getProfitHight().getRebate()+"  %");//理财师佣金  
			parames.put("dueTime", productDTO.getDueTime().toString());//产品期限//投资期限
			parames.put("issuingScale",productDTO.getAllIssuingScale().toEngineeringString());//募集规模
			parames.put("peManageOrg", productDTO.getPeManageOrg());//管理机构
			parames.put("peRevenueSharing", productDTO.getPeRevenueSharing());//收益分成
			if(productDTO.getPeManagementExpense()==null){
				parames.put("peManagementExpense", "0");
			}else{
				parames.put("peManagementExpense", (String.valueOf(productDTO.getPeManagementExpense().multiply(new BigDecimal(1.00)).doubleValue())));//管理费
			}
			
			parames.put("summary", productDTO.getSummary());//产品说明//产品介绍
			parames.put("attachments", getAttachments(productDTO.getProductId()));//文件下载
			parames.put("pRecruitmentSummary", productDTO.getpRecruitmentSummary());//募集说明
			if(StringUtils.isNotBlank(productDTO.getpRecruitmentSummary())){
				parames.put("pRecruitmentSummaryStyle","background:#FF2400; color:#fff;padding:5px;");//募集说明
			}else{
				parames.put("pRecruitmentSummaryStyle"," ");//募集说明
			}

			parames = getViewParames(parames);
			Map<String,Object> m  = MessageUtil.getMessage("newMailTemplate","shareNewMail",parames);
			String title = (String)m.get(MessageUtil.KEY_TITLE);
			String content = (String)m.get(MessageUtil.KEY_CONTENT);

			MailContentDTO mail = new MailContentDTO();
			mail.setContext(content);
			mail.setRecAddress(mailAddress);
			mail.setSubject(title+"--"+productDTO.getProductShortName());
			mail.setRequestTime(new Date());
			logger.info("===邮件发送前通知，=====");
			mailSenderService.send(mail); 
			logger.info("===邮件发送成功后，=====");
			MailRecordDTO mailRecord = new MailRecordDTO();
			mailRecord.setShareTime(new Date());
			mailRecord.setShareUserId(loginUser.getId());
			mailRecord.setShareProductId(productDTO.getProductId());
			mailRecord.setReceiverMail(mailAddress);
			mailRecord.setRemark(productDTO.getProductCode());
			productService.insertMailRecord(mailRecord);

		}catch(Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_EMAIL_SHARE_EXCEPTION);
			result.setMessage("pevc分享邮件发送失败!");
			return result;
		}
		result.setStatus(STATUS.SUCCESS);
		result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		result.setMessage("邮件发送成功！");
		return result;
	} 


	/**
	 * 将附件内容拼凑为附件链接
	 * @param pId
	 * @return
	 */
	private String getAttachments(Integer pId){
		ProductAttachmentDTO attachment = new ProductAttachmentDTO();
		attachment.setpId(pId);
		List<ProductAttachmentDTO> productAttachments = productService.getProductAttachments(attachment);
		StringBuffer attachmentsLinks = new StringBuffer();
		if(productAttachments!=null&&!productAttachments.isEmpty()){
			String fName="";
			String fPath="";
			for(ProductAttachmentDTO productAttachmentDTO:productAttachments){
				fName = productAttachmentDTO.getfName();
				fPath = PropertiesUtils.getValue("ctxPath")+productAttachmentDTO.getfPath();
				attachmentsLinks = attachmentsLinks.append("<a href='"+fPath+"' style='color:blue;padding:3px;  target='_blank'><b>"+fName+"</b></a></br>");
			}
		}
		return attachmentsLinks.toString();
	}

	/**
	 * 整理参数
	 * @param p
	 * @return
	 */
	private Map<String,Object> getViewParames(Map<String,Object> p){

		//		parames.put("annualRevenueExpect", productDTO.getAnnualRevenueExpect().toString());//预期年化收益
		String pType = (String)p.get("pType");
		String pTypeLabel = "其他";
		if(StringUtils.isNotBlank(pType)){
			if(Constants.PRODUCT_P_TYPE_PRIVATE_FUND.equals(pType)){
				pTypeLabel = "私募基金";
			}
			if(Constants.PRODUCT_P_TYPE_PRIVATE_TRUST.equals(pType)){
				pTypeLabel = "信托";
			}
			if(Constants.PRODUCT_P_TYPE_PRIVATE_EAM.equals(pType)){
				pTypeLabel = "资管计划";
			}
			if(Constants.PRODUCT_P_TYPE_PRIVATE_LP.equals(pType)){
				pTypeLabel = "有限合伙";
			}
			if(Constants.PRODUCT_P_TYPE_PRIVATE_PEVC.equals(pType)){
				pTypeLabel = "有限合伙";
			}
			p.put("pType", pTypeLabel);
		}
		
		String pProfitType = (String)p.get("pProfitType");
		String pProfitTypeLabel = "其他";
		if(StringUtils.isNotBlank(pProfitType)){//收益类型 收益类型字段：01固定,02浮动两种
			if(Constants.PRODUCT_P_PROFIT_TYPE_FIX.equals(pProfitType)){
				pProfitTypeLabel = "固定类收益";
			}
			if(Constants.PRODUCT_P_PROFIT_TYPE_FLOAT.equals(pProfitType)){
				pProfitTypeLabel = "浮动类收益";
			}
			
			p.put("pProfitType", pProfitTypeLabel);
		}
		
		String investType = (String)p.get("investType");
		String investTypeLabel = "其他";
		if(StringUtils.isNotBlank(investType)){//投资领域&投资行业 01:房地产类 02:融资租赁 03:基础设施04:其他
			if(Constants.PRODUCT_P_INVEST_TYPE_ESTATE.equals(investType)){
				investTypeLabel = "房地产类";
			}
			if(Constants.PRODUCT_P_INVEST_TYPE_DFL.equals(investType)){
				investTypeLabel = "融资租赁 ";
			}
			if(Constants.PRODUCT_P_INVEST_TYPE_IAAS.equals(investType)){
				investTypeLabel = "基础设施";
			}
			if(Constants.PRODUCT_P_INVEST_TYPE_OTHERS.equals(investType)){
				investTypeLabel = "其他";
			}
			if(Constants.PRODUCT_P_INVEST_TYPE_CTZ.equals(investType)){
				investTypeLabel = "城投债";
			}
			if(Constants.PRODUCT_P_INVEST_TYPE_BUSINESSES.equals(investType)){
				investTypeLabel = "工商企业";
			}
			p.put("investType", investTypeLabel);
		}
		
		String paymentInterestType = (String)p.get("paymentInterestType");
		String paymentInterestTypeLabel = "其他";
		if(StringUtils.isNotBlank(paymentInterestType)){
			//付息方式 付息方式 01:按月付息、02:按季付息、03:按半年付息、04:按年付息、05:到期还本付息
//			if(Constants.PRODUCT_P_PAYMENT_TYPE_MONTH.equals(paymentInterestType)){
//				paymentInterestTypeLabel = "按月付息";
//			}
//			if(Constants.PRODUCT_P_PAYMENT_TYPE_SEASON.equals(paymentInterestType)){
//				paymentInterestTypeLabel = "按季付息";
//			}
//			if(Constants.PRODUCT_P_PAYMENT_TYPE_HALF_YEAR.equals(paymentInterestType)){
//				paymentInterestTypeLabel = "半年付息";
//			}
//			if(Constants.PRODUCT_P_PAYMENT_TYPE_YEAR.equals(paymentInterestType)){
//				paymentInterestTypeLabel = "按年付息";
//			}
//			if(Constants.PRODUCT_P_PAYMENT_TYPE_ALL.equals(paymentInterestType)){
//				paymentInterestTypeLabel = "到期还本付息";
//			}
			paymentInterestTypeLabel = CommonConstantUtil.getPaymentInterestTypeDesc(paymentInterestType);
			p.put("paymentInterestType", paymentInterestTypeLabel);
		}
		String issuingScale = (String)p.get("issuingScale");//募集规模
		if(StringUtils.isNotBlank(issuingScale)){
			Double issuingScaleDouble = Double.valueOf(issuingScale);
			Double y = (issuingScaleDouble/100000000);
			if(y>0){
				p.put("issuingScale",  y +" 亿元");
			}else{
				Double w = (issuingScaleDouble/10000);
				p.put("issuingScale",  w +" 万元");
			}
		}
		//01江浙沪；02京津冀；03珠三角；04其他地区'
		String publicArea=(String) p.get("publicArea");
		String publicZone="";
		if(StringUtils.isNotBlank(publicArea)){
			if(Constants.PUBLIC_AREA_JZH.equals(publicArea)){
				publicZone = "江浙沪";
			}
			if(Constants.PUBLIC_AREA_JJJ.equals(publicArea)){
				publicZone = "京津冀";
			}
			if(Constants.PUBLIC_AREA_ZSJ.equals(publicArea)){
				publicZone = "珠三角";
			}
			if(Constants.PUBLIC_AREA_QT.equals(publicArea)){
				publicZone = "其他地区";
			}
			if(Constants.PUBLIC_AREA_QG.equals(publicArea)){
				publicZone = "全国";
			}
			
			p.put("publicArea", publicZone);
		}
		
		//isAgreement是否为协议价的标志rebate
		String isAgreement=(String) p.get("isAgreement");
		String rebate=(String) p.get("rebate");
		if(StringUtils.isNotBlank(isAgreement)){
			if(Constants.IS_AGREEMENT_XY.equals(isAgreement)){
				rebate="协议价";
			}
			p.put("rebate", rebate);
		}
		
		//peOrganizeShape, 组织形式 01:信托，02:券商资管，03:有限合伙人,04:契约性基金,05：基金子公司,06:其他
		
		String peOrganizeShape=(String) p.get("peOrganizeShape");
		String peOrganizeState="";
		if(StringUtils.isNotBlank(publicArea)){
			if(Constants.PE_ORGANIZE_SHAPE_XT.equals(peOrganizeShape)){
				peOrganizeState = "信托";
			}
			if(Constants.PE_ORGANIZE_SHAPE_JSZG.equals(peOrganizeShape)){
				peOrganizeState = "券商资管";
			}
			if(Constants.PE_ORGANIZE_SHAPE_YXHHR.equals(peOrganizeShape)){
				peOrganizeState = "有限合伙人";
			}
			if(Constants.PE_ORGANIZE_SHAPE_QYXJJ.equals(peOrganizeShape)){
				peOrganizeState = "契约性基金";
			}
			if(Constants.PE_ORGANIZE_SHAPE_JJZGS.equals(peOrganizeShape)){
				peOrganizeState = "基金子公司";
			}
			if(Constants.PE_ORGANIZE_SHAPE_QT.equals(peOrganizeShape)){
				peOrganizeState = "其他";
			}
			p.put("peOrganizeShape", peOrganizeState);
		}
		
		// saleStatus：募集状态（01:未开始02:预售中，03:募集中 04:已募满 05:募集结束'）
		
		String saleStatus=(String) p.get("saleStatus");
		String saleCondition="";
		if(StringUtils.isNotBlank(saleStatus)){
			if(Constants.SALE_STATUS_WKS.equals(saleStatus)){
				saleCondition = "未开始";
			}
			if(Constants.SALE_STATUS_YSZ.equals(saleStatus)){
				saleCondition = "预热中";
			}
			if(Constants.SALE_STATUS_MJZ.equals(saleStatus)){
				saleCondition = "募集中";
			}
			if(Constants.SALE_STATUS_YMM.equals(saleStatus)){
				saleCondition = "已募满";
			}
			if(Constants.SALE_STATUS_MJJS.equals(saleStatus)){
				saleCondition = "募集结束";
			}
			
			p.put("saleStatus", saleCondition);
		}
		return p;
	}
	
	/**
	 * 
	 * 2016 元宵活动
	 * @return
	 */
	@RequestMapping(value="/ylyxhd")
	@ResponseBody
	public ResultMap ylyxhdSend(HttpServletRequest request, HttpServletResponse response,RegisterDTO registerDto,String createsCode){ 
		ResultMap result = new ResultMap();
		try {
			if(StringUtils.isBlank(createsCode)){
				//空  默认是 2016元宵活动
				createsCode = ActivitiesYLYXHDImpl.activitiesCode;
			}
			//参数验证
			if(StringUtils.isBlank(registerDto.getMobile())){
				
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("mobile is null!");
				return result;
			}
			
			
			//活动来源  前端传递
			registerDto.setActSource(createsCode);
			
			//校验验证码   测试环境开关是否开启，关闭不校验验证码
			//checkCodeServiceImpl.CheckCodeSwitch()
			if(checkCodeServiceImpl.CheckCodeSwitch()){
				Integer activety_otp_time= new Integer(PropertiesUtils.getValue("activety_otp_time"));
				//验证码超时
				if(checkOtpCodeTimeOut(registerDto.getMobile(),activety_otp_time,ISmsService.OTP_CODE_FIRST_TIME)){
					result.setStatus(ResultMap.STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_OTP_VALIDATE_ERROR_TIMEOUT);
					result.setMessage("手机验证码超时！");
					return result;
					
				};
				ResultMap resultOtp = checkOtpCode(registerDto.getMobile(),registerDto.getvCode());
				if(!STATUS.SUCCESS.equals(resultOtp.getStatus())){
					result.setStatus(resultOtp.getStatus());
					result.setStatusCode(resultOtp.getStatusCode());
					result.setMessage(resultOtp.getMessage());
					return result;
				}
			}
			
			//是否注册
			boolean mobileRegistered = userService.isMobileRegistered(registerDto.getMobile());
			UserDTO user=new UserDTO();
			boolean isNewUser = false;
			if(!mobileRegistered){
				//自动注册
				isNewUser = true;
				String pwd="sfa"+RandomUtils.getRandomUtils(6);
				logger.debug(registerDto.getMobile()+"自动生成密码:"+pwd);
				registerDto.setPassword(pwd);
				//未注册 自动注册
				UserDTO userLogin=registerService.doRegister(registerDto);
				result.setAttribute("uImage", userLogin.getuImage());
				result.setAttribute("isNewUser", isNewUser);
				
				String msgContent="您好，您已参与超级理财师红包活动。您可使用手机账号和密码("+pwd+"),登陆超级理财师官方网站www.superfa.cn。如有疑问请电询400-855-8085";
				logger.info(msgContent);
				try {
					smsService.sendOtpMessage(registerDto.getMobile(),msgContent,Constants.regPasswdSmsAd);
				} catch (Exception e) {
					logger.error("send regpasswdsmsadd error",e);
				}
				user=userLogin;
			}else{
				user.setLoginName(registerDto.getMobile());
				//查询用户信息
				user = userService.queryUserByMobile(user);
			}
			
			
			//判断该手机是否绑定过
			FaUserWechatDTO bean = new FaUserWechatDTO();
			bean.setUserId(user.getId());
			if(userWechatServiceImpl.queryUserWechatInfo(bean) != null){
				logger.info("In apiweixin relationlogin checkUser Have bound");
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_WECHAT_ALREADY_USER_ERROR);
				result.setMessage("用户已经绑定!");
				return result;
			}
			
			//微信绑定
			result =wechatCoreServiceImpl.relationWechat(user.getId());
			//关联失败直接返回
			if(STATUS.FAILE.equals(result.getStatus())){
				logger.info("In apiweixin ylyxhdSend relationWechat FAILE!");
				return result;
			}
			
			//自动登录  存储  session
			autoLogin(request, user);
			
			result.setAttribute("id", user.getId());
			result.setAttribute("role", user.getRole());
			logger.info("userId"+user.getId()+"==="+user.getLoginName()+"==="+user.getMobile());
			
			//注入活动
			try {
				HashMap<String,Object> map = new HashMap<String,Object>();
				map.put("faUser", user);
				map.put("isNewUser", isNewUser);
				activitesServiceImpl.ActivitiesJobExecutionObject(ActivitiesBusinessObject.handle_ylyxhd, map);
			} catch (Exception e) {
				log.error("ylyxhdSend ActivitiesJobExecutionObejct error", e);
			}
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		} catch (Exception e) {
			logger.error("ylyxhd messang error:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return result;

	}
	/**
	 * 
	 * 2016 元宵活动
	 * @return
	 */
	@RequestMapping(value="/ylyxhdSuccess")
	@ResponseBody
	public ResultMap ylyxhdSuccess(HttpServletRequest request, HttpServletResponse response,RegisterDTO registerDto){ 
		ResultMap result = new ResultMap();
		try {
			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			
			if(loginUser == null){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_ONLOGIN);
				result.setMessage("未登录");
				return result;
			}
			
			//注入活动
			try {
				HashMap<String,Object> map = new HashMap<String,Object>();
				map.put("faUser", loginUser);
				map.put("isNewUser", false);
				activitesServiceImpl.ActivitiesJobExecutionObject(ActivitiesBusinessObject.handle_ylyxhd, map);
			} catch (Exception e) {
				log.error("ylyxhdSuccess ActivitiesJobExecutionObejct error", e);
			}
			result.setAttribute("userId", loginUser.getId());
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		} catch (Exception e) {
			logger.error("ylyxhdSuccess messang error:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return result;

	}
	/**
	 * 
	 * 2016 元宵活动
	 * @return
	 */
	@RequestMapping(value="/ylyxhdInfo")
	@ResponseBody
	public ResultMap ylyxhdInfo(HttpServletRequest request, HttpServletResponse response,RegisterDTO registerDto,String createsCode){ 
		ResultMap result = new ResultMap();
		try {
			
			//活动来源
			if(StringUtils.isBlank(createsCode)){
				//空  默认是 2016元宵活动
				createsCode = ActivitiesYLYXHDImpl.activitiesCode;
			}
			
			//判断活动
			int actFlag = activitieGiftServiceImpl.isActivitieEnd(createsCode);
			if(actFlag== 1)	{
				// 活动已结束
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setAttribute("status", ResultMap.ACTIVITIES_DATE_IS_OUT);
				result.setMessage("活动已结束");
				return result;
			}else if(actFlag == 2){
				// 奖金池已耗光
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setAttribute("status", ResultMap.ACTIVITIES_DATE_IS_OUT);
				result.setMessage("奖金池已耗光");
				return result;
			}
			ylyxhd_count.getAndIncrement();
			result.setAttribute("hdCount", ylyxhd_count.get());
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		} catch (Exception e) {
			logger.error("ylyxhdInfo messang error:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return result;

	}
}
